var app = getApp();
import { $init, $digest } from '../../../js/common.util'
var config = require('../../../config.js');
Page({
  data: {
    t_length: 0,
    content: '',
    cellPhone: '',
    images: [],
    titleCount: 0,
    contentCount: 0,
    title: '',
    str:''
  },
  bindText(e) {
    var t_text = e.detail.value;
    this.setData({
      t_length: t_text.length,
      content: t_text
    })
  },
  cellPhoneInput(e) {
    this.setData({
      cellPhone: e.detail.value
    })
  },
  onLoad: function (options) {
    $init(this)
  },
  chooseImage(e) {
    wx.chooseImage({
      count: 4,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        const images = this.data.images.concat(res.tempFilePaths)
        this.data.images = images.length <= 4 ? images : images.slice(0, 4)
        $digest(this)
      }
    })
  },
  removeImage(e) {
    const idx = e.target.dataset.idx
    this.data.images.splice(idx, 1)
    $digest(this)
  },
  handleImagePreview(e) {
    const idx = e.target.dataset.idx
    const images = this.data.images
    wx.previewImage({
      current: images[idx],
      urls: images,
    })
  },
  submitContent() {
    const cellPhone = this.data.cellPhone
    const content = this.data.content
    const strs = this.data.str
      app.request({
        url: 'api/wechat/message',
        method: "GET",
        data: {
          cellPhone: cellPhone,
          content: content,
          pic: strs
        },
        success: function (res) {
          if (res.data.result) {
            wx.showModal({
              showCancel: false,
              content: '发送成功！',
              success: (res) => {
                wx.switchTab({
                  url: '/page/UserCenter/index',
                })
              },
            })
          } else {
            wx.showToast({
              title: '请稍后重试！',
              icon: 'none'
            })
          }
        }
      })
  },
  uploadImgs(){
    var self = this
    var str = ""
    return new Promise(function (resolve, reject){
      for (var i = 0; i < self.data.images.length; i++) {
        wx.uploadFile({
          url: config.apiUrl + 'api/wechat/uploadImg',
          filePath: self.data.images[i],
          async: false,
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'cookie': wx.getStorageSync("cookie")
          },
          name: 'content',
          success: function (res) {
            var res = JSON.parse(res.data)
            if (res.data.result) {
              str += res.data.file_name + ","
              self.setData({
                str:str
              })
            }
          }
        })
      }
    })
  },
  submit(e) {
    let self = this
    const content = this.data.content
    if (content == '') {
      wx.showToast({ title: '请输入内容！', icon: 'none', duration: 3000 });
      return;
    }

    if (content) {
      const arr = []
      if (this.data.images.length > 0){

        wx.showLoading({
          title: '正在创建...',
          mask: true
        })
        for (let path of this.data.images) {
          arr.push(new Promise(function (resolve, reject) {
            wx.uploadFile({
              url: config.apiUrl + 'api/wechat/uploadImg',
              filePath: path,
              header: {
                'content-type': 'application/x-www-form-urlencoded',
                'cookie': wx.getStorageSync("cookie")
              },
              name: 'content',
              success(res) {
                var res = JSON.parse(res.data)
                if (res.data.result) {
                  var str = self.data.str
                  str += res.data.file_name + ","
                  self.setData({
                    str: str
                  })
                  console.log(self.data.str)
                }
                resolve()
              },
            })
          }))
        }
        Promise.all(arr).then(res => {
          console.log("图片上传完成后再执行")
          console.log(self.data.str)
          self.submitContent()
        }).catch(err => {
          console.log(">>>> upload images error:", err)
        })
      }else{
        self.submitContent()
      }
    }
  }
})